<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '详情',
    enablePullDownRefresh: false,
  },
}
</route>
<template>
  <view class="page">
    <view class="px-4">
      <view class="text-base font-bold text-[40rpx]">{{ article?.row.title }}</view>
      <view class="flex items-end justify-between mt-2">
        <text class="text-[#9A9A9A] text-xs">{{ article?.row.create_time }}</text>
        <view class="flex gap-x-[40rpx]" v-if="article?.row">
          <share-button></share-button>
          <collect-button
            api="/shopapi/collect/handleCollectarticle"
            v-model="article.row.is_collect"
            :params="{ article_id: article?.row.id, is_collect: Number(!article?.row.is_collect) }"
          ></collect-button>
        </view>
      </view>
    </view>
    <view class="leading-relaxed text-sm px-4 mt-[20rpx]">
      <uv-parse :content="imgDeal(article?.row.content)"></uv-parse>
    </view>

    <view class="mt-[50rpx]">
      <view class="review-header">
        <text class="review-header-label">
          评论
          <text class="text-[26rpx] font-normal">({{ article?.count }})</text>
        </text>
      </view>
      <view class="px-4 mt-1" v-if="commentList.length">
        <review-list
          :data="commentList"
          @recover="handleRecover"
          @open="handleOpenReview"
        ></review-list>
      </view>
    </view>

    <float-bottom
      v-if="!userStore.systemConfig.is_check"
      customClass="min-h-[116rpx] max-h-[300rpx]"
    >
      <view
        class="min-h-[116rpx] flex items-center px-4 border-[#F2F2F2] border-t-solid border-t-1"
      >
        <view class="flex-1 bg-[#f4f4f4] px-2 rounded-sm mr-2">
          <wd-textarea
            v-model="state.content"
            :placeholder="placeholder"
            :clearable="true"
            :auto-height="true"
            :focusWhenClear="true"
            :focus="state.focus"
            :no-border="true"
            :maxlength="200"
            @blur="handleCancelFocus"
          />
        </view>

        <wd-button :round="false" size="small" @click="handleSendReview">发送</wd-button>
      </view>
    </float-bottom>
  </view>
</template>

<script setup>
import useRequest from '@/hooks/useRequest'
import { fetchArticleDetail, articleComment, fetchCommentList } from '@/service/article'
import useReachBottomLoadMore from '@/hooks/useReachBottomLoadMore'
import { showToast } from '@/utils/uni'
import { imgDeal } from '@/utils/format'
import { useUserStore } from '@/store'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
const userStore = useUserStore()
const { data: article, run } = useRequest(fetchArticleDetail)

const state = ref({
  articleId: '',
  focus: false,
  content: '',
  recoverUser: null,
})

const placeholder = computed(() => {
  const { recoverUser } = state.value
  if (recoverUser) return `回复：${recoverUser.nickname}`
  return '请输入评论内容'
})

const requestParams = computed(() => {
  const { articleId } = state.value
  return {
    article_id: articleId,
  }
})

const { data: commentList } = useReachBottomLoadMore(fetchCommentList, requestParams)

function handleOpenReview({ item, index }) {
  commentList.value[index].showReview = !commentList.value[index].showReview

  if (!commentList.value[index].showReview) return
  getChildCommentList({ article_comment_id: item.id }, (data) => {
    commentList.value[index].children = data
  })
}

function handleRecover(item) {
  state.value.recoverUser = item
  state.value.focus = true
}

function handleCancelFocus() {
  state.value.focus = false
}

function getChildCommentList(params = {}, callback) {
  const { articleId } = state.value
  fetchCommentList({ article_id: articleId, ...params }).then((res) => {
    const { lists } = res.data
    if (typeof callback == 'function') {
      callback(lists)
    }
  })
}

function handleSendReview() {
  const { recoverUser, content } = state.value
  if (!content) return showToast('请输入评论内容')
  const { articleId } = state.value

  const params = {
    article_id: articleId,
    comment: content,
  }

  if (state.value.recoverUser) {
    params.reply_id = recoverUser.id
  }

  articleComment(params).then((res) => {
    const { row } = res.data
    if (recoverUser) {
      const replyId = recoverUser.reply_id || recoverUser.id
      const index = commentList.value.findIndex((item) => item.id == replyId)
      if (index >= 0) {
        if (Array.isArray(commentList.value[index].children)) {
          commentList.value[index].children.unshift(row)
        } else {
          commentList.value[index].children = [row]
        }
      }
    } else {
      commentList.value.unshift(row)
    }

    state.value.content = ''
    state.value.recoverUser = null
    showToast(res.msg)
  })
}

onLoad(({ id }) => {
  state.value.articleId = id
  run(id)
  // getCommentData();
})
</script>

<style lang="scss" scoped>
::v-deep .review-input {
  padding: 0 !important;
  margin-right: 20rpx;
  border-radius: 4rpx;
}

.page {
  @include addSafeArea(146rpx);

  .review-header {
    @apply text-md text-base pb-2 border-b-solid border-b-1 border-[#EDEDED] px-4;

    &-label {
      @apply relative font-boldm;

      &::after {
        bottom: -16rpx;
        height: 6rpx;
        content: '';
        border-radius: 3rpx;
        @apply w-1/2 bg-primary absolute left-1/2 transform -translate-x-1/2;
      }
    }
  }
}
</style>
